import os
from PIL import Image


def rotate_and_convert_to_pdf():
    # 获取当前目录下所有jpg/jpeg/png图片（不区分大小写）
    image_files = [f for f in os.listdir()
                   if f.lower().endswith(('.jpg', '.jpeg', '.png'))]

    if not image_files:
        print("未找到图片文件")
        return

    # 创建临时旋转后的图片列表
    rotated_images = []

    for img_file in sorted(image_files):
        try:
            with Image.open(img_file) as img:
                # 旋转90度（顺时针）并自动调整画布大小
                rotated = img.rotate(-90, expand=True)
                if img.mode != 'RGB':
                    rotated = rotated.convert('RGB')
                rotated_images.append(rotated)
        except Exception as e:
            print(f"处理 {img_file} 时出错: {str(e)}")

    if rotated_images:
        # 保存为PDF（使用第一张图片作为基准）
        output_name = "rotated_merged.pdf"
        rotated_images[0].save(
            output_name,
            save_all=True,
            append_images=rotated_images[1:]
        )
        print(f"已生成: {output_name} (包含{len(rotated_images)}页)")


# 执行转换
rotate_and_convert_to_pdf()